import MSDBTemplates
import kinterbasdb; kinterbasdb.init(type_conv=200)

def getDBConnection(DBPath, DBUser, DBPass, DBConnReestablishmentDelay=5, DBConnReestablishmentAttemptCount=3):
    attemptCount = 0
    conn = None
    while True:
        try:    
            conn = kinterbasdb.connect(dsn=DBPath, user=DBUser, password=DBPass)
            break
        except:
            secs = DBConnReestablishmentDelay
            attemptCount += 1
            if attemptCount > DBConnReestablishmentAttemptCount:
                attemptCount = 0
                secs *= 10
            logWarn('PCN connect failed: sleep %d secs before new attempt' % (secs))
            sleep(secs)
    return conn

def checkDBConnection(oldConn, DBPath, DBUser, DBPass):
    if oldConn == None:
        logDebug('setting up new connection to PCN DB')
        oldConn = getDBConnection(DBPath, DBUser, DBPass)
    if oldConn.closed:
        logDebug('reestablish connection to PCN DB')
        oldConn = getDBConnection(DBPath, DBUser, DBPass)
    return oldConn

def storeStaticEvents(Events, DBConnection, DBPath, DBUser, DBPass):
    if Events == None or len(Events)==0:
        return DBConnection
    try:
        DBConnection = checkDBConnection(DBConnection, DBPath, DBUser, DBPass)
        DBCursor = None
        DBCursor = DBConnection.cursor()
        recId = MSDBTemplates.get_FromSGN_LastRecId(DBCursor)
        Events.sort()
        for e in Events:
            e.userWriterId = str(DBUser)
            recId = MSDBTemplates.store_MSEvent_ToSGN(e, DBCursor, recId)
        DBConnection.commit()
    except (Exception), err:
        logError('failed to store events with exception: %s' % str(err))
    return DBConnection
